import urllib.request
import csv
import json
import requests

#def getHtml(url):
#   html = urllib.request.urlopen(url).read()
#   return html

#def saveHtml(file_name, file_content):
#    with open(file_name.replace('/', '_') + ".html", "wb") as f:
#    f.write(file_content)

#aurl = "https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_aladin_banner#tab4"
#html = getHtml(aurl)
#saveHtml("sduview", html)

todayKey = 'today'
totalKey = 'total'
confirmKey = 'confirm'
nowConfirmKey = 'nowConfirm'
nameKey = 'name'
childrenKey = 'children'
ExcelName = '疫情日报.csv'

api = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'


if __name__ == '__main__':
    datas = json.loads(requests.get(url=api).json()['data'])
    with open(ExcelName, 'w', encoding='utf-8', newline='') as csvfile:
        writer = csv.writer(csvfile)
        dataLog = '更新时间：' + datas['lastUpdateTime']
        writer.writerow([dataLog])
        for contry in datas['areaTree']:
            if contry[nameKey] == '中国':
                for province in contry[childrenKey]:
                    provinceName = str(province[nameKey])
                    newConfirm = str(province[todayKey][confirmKey])
                    nowConfirm = str(province[totalKey][nowConfirmKey])
                    writer.writerow([str('\t' + provinceName + ' 新增确诊: '
                                         + newConfirm + ', 现有确诊：' + nowConfirm)])
                    for city in province[childrenKey]:
                        newConfirm = str(city[todayKey][confirmKey])
                        nowConfirm = str(city[totalKey][nowConfirmKey])
                        cityName = city[nameKey]
                        writer.writerow([str('\t\t' + cityName + ' \t\t新增确诊:' + newConfirm
                                             + ',\t现有确诊：' + nowConfirm)])

